<?php
/**
 * ZjhSyncDumpPlayerData.php
 * @Func: Dump player's data from Redis to Mysql for data persistence
 * @Boot: nohup php ZjhSyncDumpPlayerData.php > /dev/null &
 * @Auth: 啊烦
 * @Data: 2016-11-11
 */
 /*
$mutex = Mutex::create();
if($mutex){
   exit;
   Mutex::destroy($mutex);	
}*/

if ( !defined("SCRIPT_DIR") ) {
	define("SCRIPT_DIR", dirname(__FILE__));
}
$path = explode('/',__FILE__);
if ( !defined("FILE") ) {
	define("FILE",end($path));
}

function path_format($file) {
	return SCRIPT_DIR . '/' . $file;
}


include_once(path_format('lib/logger.php'));
include_once(path_format('config/config.php'));
include_once(path_format('lib/mysql.php'));
include_once(path_format('lib/redis.php'));
class SyncConf {
	public static $sync_sec = 30;//回写数据库时间
	public static $hlen = 20;
	public static $logout_diff =86400; //86400秒 = 一天， logout_diff时间内无活动删除redis  857019
	public static $begin = 0;
	public static $end = 0;//
}



function sync() {
	//初始化mysql
    $mysql = new MysqlDriver();
	$ret = $mysql->connect(Config::$mysql_config);
	if ( !$ret ) {
		Config::$loggerError->error(FILE, "connect mysql error.");
	}

	//初始化cache redis
	$cache_redis = new RedisDriver();
    $ret = $cache_redis->initCacheRedis(0);
    if (!$ret) {
        Config::$loggerError->error(FILE, "initCacheRedis error");
    }

	$mod = Config::$mod;
    $total = 0;//在线总人数
	static $playerarr = array();
	for ($i = 0; $i < Config::$mod; $i++) {
		//初始化data redis
		$redis = new RedisDriver();
		$ret = $redis->initDataRedis($i);
		if (!$ret){
			Config::$loggerError->error(FILE, "initDataRedis error");
			continue;
		}
		//同步hu:*缓存数据到数据库  
		$keys = $redis->data_redis->keys('hu:*');

		//获得所有hu:xxx, 过滤hu:xxx:xxx
		$keys_size = count($keys);
		$keys2 = array();

	    for($e=0;$e<$keys_size;$e++){
			if(substr_count($keys[$e],':')<2){
			  $keys2[]=$keys[$e];
			}
		}

		$keys =  $keys2;
        $keys_size = count($keys);

		if ($keys_size <= 0) {
			continue;
		}   

		for ($j = 0; $j < $keys_size; $j++ ) {
			$key = $keys[$j];
			$hlen = $redis->data_redis->hLen($key);
			if ($hlen < SyncConf::$hlen) {
				$redis->data_redis->delete($key);

			} else {
				$player = $redis->data_redis->hMget($key, array('id','isrobot','skey','login_days','is_get_login_reward','name','sex',
				'heartbeat_at','update_time','is_vip','login_ip','register_ip','avater_url','payment','point','is_visitor'));           
			
				if(!$player['isrobot']){ 
                    /*
					if(array_key_exists($player['id'],$playerarr)){
						$tmp = array("money"=>$player['money'],'coin'=>$player['coin']);
						
						if((int)$playerarr[$player['id']]['money']!=(int)$player['money'] || (int)$playerarr[$player['id']]['coin']!=(int)$player['coin']){
						
						  $playerarr[$player['id']]=$tmp;

						
						}

					}else{
					   $tmp2 = array("money"=>$player['money'],'coin'=>$player['coin']);
					   $playerarr[$player['id']] = $tmp2;
			
						
					}
				    */
				}

				unset($player['isrobot']);
		
				//在线人数统计
                /*
                $online_user = $redis->data_redis->hMget($key, array('online_vid','id'));
				$rownum = $mysql->select("onlineplayer", "*", array('uid' => $online_user['id']));
				$roomid = $rownum[0]['roomid'];
				if($online_user['online_vid']){
                    //Config::$log->info(FILE,'在线人数'.$online_user['online_vid']);
					if(count($rownum)==0){
					  $addonlineuser = array('uid'=>$online_user['id'],'roomid'=>$online_user['online_vid']);	
					  $mysql->insert("onlineplayer", $addonlineuser);
					  //Config::$log->info(FILE,'在线');
					}else{
						
					  $where = 	array('uid'=>$online_user['id']);	
					  $ondata = array('roomid'=>$online_user['online_vid']);
					  $mysql->update('onlineplayer',$ondata, $where);						  
					}
				}else{
					if(count($rownum)>0){
					  $mysql->query("delete from onlineplayer where uid=".$online_user['id']."");
					  //Config::$log->info(FILE,'不在线');
					}
				}
				*/
				$id=$player['id'];
				unset($player['id']);
				$where = array();
				$where['id'] = $id;
				$mysql->update('player', $player, $where);
				

				
				//游戏玩局记录
				$isExists = $redis->data_redis->exists("$key:match");
                if($isExists){
					$matchdata = $redis->data_redis->hGetAll("$key:match");
					$result = $mysql->find("select * from player_game where user_id=".$matchdata['user_id']);
					$data = array('user_id'=>$matchdata['user_id'],'win_count'=>$matchdata['win_count'],'lose_count'=>$matchdata['lose_count'],
						'winning_streak'=>$matchdata['winning_streak'],'highest_winning_streak'=>$matchdata['highest_winning_streak']);
					if(empty($result)){
						$mysql->insert("player_game",$data);
					}else{
						$mysql->update("player_game",$data,array('id'=>$result[0]['id']));
					}
				}

			}
            
			//删除玩家 redis key数据,但不删除机器人的redis数据
			if ($id > SyncConf::$begin && $id <= SyncConf::$end) {	

			} else {
				$diff = time() - (int)$player['heartbeat_at'];
                
				if ($diff>=SyncConf::$logout_diff) {
					//删除玩家redis记录
					$redis->data_redis->delete($key);
			        

					//删除游戏redis记录
					$arr = $redis->data_redis->keys("$key:*");
                    if(!empty($arr)){
						foreach($arr as $v){
							$redis->data_redis->delete($v);
						}
					}				
					
					//删除玩家背包redis记录
                    $hbackpack = $cache_redis->cache_redis->keys("hbackpack:".$id.":*");
					$hbackpack_count = count($hbackpack);
					if($hbackpack_count>0){
						for($r=1;$r<=$hbackpack_count;$r++){
						    $cache_redis->cache_redis->delete("hbackpack:".$id.":$r");
					    }
					}

					//删除玩家邮件redis记录
					$hemailbyuser = $cache_redis->cache_redis->keys("hemailbyuser:".$id.":*");
					$hemailbyuser_count = count($hemailbyuser);
					if($hemailbyuser_count>0){
						for($r=1;$r<=$hemailbyuser_count;$r++){
						    $cache_redis->cache_redis->delete("hemailbyuser:".$id.":$r");
					    }
					}
					$keys_size--;
				}				
			}	
			
		 //$total = $total+$keys_size;					
		}
	}
	//$cache_redis->cache_redis->hSet('playing','total',$total);
	$redis->deinitDataRedis();
	$cache_redis->deinitCacheRedis();
	$mysql->close();

}


function main(){
	while(1) {
		sync();	
		echo date('Y:m:d H:i:s')." ZjhSyncDumpPlayerData working...\r\n"; 	
		$sync_sec = SyncConf::$sync_sec;
		sleep($sync_sec);
		
	}
}


main();

?>
